#include "device.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>

// 设备链表头指针
DeviceManager *head = NULL;

// 添加设备
void add_device(DeviceType type, const char *name) {
    DeviceManager *new_device = (DeviceManager*)malloc(sizeof(DeviceManager));
    if (new_device == NULL) {
        fprintf(stderr, "内存分配失败\n");
        exit(1);
    }
    static int device_count = 0;
    new_device->id = ++device_count;
    new_device->Type = type;
    strncpy(new_device->name, name, sizeof(new_device->name) - 1);
    new_device->name[sizeof(new_device->name) - 1] = '\0';
    new_device->value = 0.0;
    new_device->next = NULL;

    if (head == NULL) {
        head = new_device;
    } else {
        DeviceManager *temp = head;
        while (temp->next != NULL) {
            temp = temp->next;
        }
        temp->next = new_device;
    }
}

// 根据类型查找设备
DeviceManager* find_device_by_type(DeviceType type) {
    DeviceManager *current = head;
    while (current != NULL) {
        if (current->Type == type) {
            return current;
        }
        current = current->next;
    }
    return NULL;
}

// 释放所有设备
void free_all_devices() {
    DeviceManager *current = head;
    while (current != NULL) {
        DeviceManager *next = current->next;
        free(current);
        current = next;
    }
    head = NULL;
}